package com.spring.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @version 1.0.0
 * @Date: 2022/7/17 21:08
 * @Author ZhuYouBin
 * @Description
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping("/file")
    public String upload(HttpSession session, MultipartFile file) throws IOException {
        // 获取上下文对象
        ServletContext context = session.getServletContext();
        // 获取文件上传路径
        String upload = context.getRealPath("upload");
        // 将文件上传到 upload 目录下面
        String filename = file.getOriginalFilename();
        File uploadFile = new File(upload + "/" + filename);
        file.transferTo(uploadFile);
        System.out.println("上传成功");
        return "";
    }

    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 1、获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        // 2、设置响应类型, 设置文件名称
//        response.setHeader("Content-Disposition", "attachment;filename=1.jpg");
        // 解决文件名称中文乱码问题
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1.jpg", "utf-8"));
        // 3、读取 upload 目录下面的图片文件
        String realPath = request.getSession().getServletContext().getRealPath("upload");
        File file = new File(realPath + "/1.jpg");
        // 4、创建文件输入流
        FileInputStream fis = new FileInputStream(file);
        // 5、将输入流通过输出流响应给浏览器
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {
            // 写入输出流
            out.write(bytes, 0, len);
        }
        // 6、读取完成之后, 关闭输出流
        fis.close();
        out.close();
    }

}
